import React, { useState, useEffect } from'react';
import { useNavigate } from'react-router-dom';
import { 
  fetchStrategyList, 
  fetchCollectData, 
  fetchAllCollectData,
  deleteCollectItem 
} from '../api/browse'; 
import { 
fetchScenicData
} from '../api/scenicData'; 
// 图片资源导入
import leftImg from '../assets/left.png';
import hourse3Img from '../assets/hourse3.png';
import rbsImg from '../assets/rubbish.png';
import defaultimg from '../assets/pandaback.png';
import { imgUrl } from '../config'; // 导入imgUrl
/**
 * 浏览记录组件 - 展示用户收藏和点赞的景点内容
 * 支持切换不同类型的内容展示（全部、收藏、点赞）
 * 提供内容删除功能和景区详情跳转
 */
const BrowseRecord = () => {
  const navigate = useNavigate(); // 路由导航钩子

  // 组件状态管理
  const [activeTab, setActiveTab] = useState(0);           // 当前激活的选项卡索引
  const [scenicList, setScenicList] = useState([]);       // 景点列表数据
  const [strategyList, setStrategyList] = useState([]);   // 攻略列表数据
  const [filteredData, setFilteredData] = useState([]);   // 过滤后的收藏/点赞数据
  const [loading, setLoading] = useState(true);           // 加载状态标识
  const [pageTitle, setPageTitle] = useState("我的收藏");  // 页面标题
  const [scenicMap, setScenicMap] = useState({});         // 景点ID到景点信息的映射表
  const [strategyMap, setStrategyMap] = useState({});     // 攻略ID到攻略信息的映射表

  // 选项卡配置定义
  const tabs = [
    { name: "全部", status: 1, type: null },    // 显示所有收藏和点赞内容
    { name: "收藏", status: 1, type: 1 },      // 只显示收藏内容
    { name: "点赞", status: 1, type: 3 }       // 只显示点赞内容
  ];

  // 导航功能
  const goBack = () => navigate(-1);        // 返回上一页
  const goHome = () => navigate("/home");   // 跳转到首页

  /**
   * 组件初始化副作用
   * 1. 获取景点列表和攻略列表
   * 2. 构建ID到信息的映射表
   * 3. 初始化选项卡数据
   */
 useEffect(() => {
  const userId = sessionStorage.getItem("userid");

  // 链式获取景点和攻略数据
  fetchScenicData()
    .then(res => {
      // axios 返回的数据可能在 res.data 中，需要检查
      const scenicData = res.data || res; // 兼容处理
      
      // 构建景点ID到景点信息的映射
      const map = {};
      scenicData.forEach(scenic => {
        map[scenic.id] = scenic;
      });
      setScenicMap(map);
      setScenicList(scenicData);

      // 继续获取攻略列表
      return fetchStrategyList(3); // 传3获取所有攻略
    })
    .then(introRes => {
      // 同样处理攻略数据
      const strategyData = introRes.data || introRes;
      
      // 构建攻略ID到攻略信息的映射
      const introMap = {};
      strategyData.forEach(intro => {
        introMap[intro.id] = intro;
      });
      setStrategyMap(introMap);
      setStrategyList(strategyData);

      // 初始化选项卡数据
      handleTabClick(0, tabs[0].status, tabs[0].type);
      setPageTitle(tabs[0].name);
    })
    .catch(error => {
      console.error('初始化数据出错:', error);
      setLoading(false);
    });
}, []);

  /**
   * 获取特定类型的收藏/点赞数据
   * @param {number} userId - 用户ID
   * @param {number} type - 数据类型(1:收藏,3:点赞)
   */
 const fetchCollectDataWrapper = (userId, type) => {
  setLoading(true);
  fetchCollectData(userId, type)
    .then(res => {
      // 安全处理可能不存在的数据
      const data = res.data || res || []; // 多层兼容处理

      // 关联攻略和景点信息
      const processedData = data.map(item => {
        let scenicInfo = {};
        // 通过攻略ID查找对应的景点信息
        if (item.intro_id) {
          const intro = strategyMap[item.intro_id];
          if (intro) {
            scenicInfo = scenicMap[intro.scenic_id] || {};
          }
        }
        return {
          ...item,
          scenicInfo
        };
      });
      
      setFilteredData(processedData);
      setLoading(false);
    })
    .catch(error => {
      console.error('获取收藏/点赞列表出错:', error);
      setFilteredData([]); // 出错时显示空列表
      setLoading(false);
    });
};
  /**
   * 获取所有收藏和点赞数据
   * @param {number} userId - 用户ID
   */
 const fetchAllDataWrapper = (userId) => {
  setLoading(true);
  fetchAllCollectData(userId)
    .then(uniqueData => {
      // 确保 uniqueData 是数组
      const data = Array.isArray(uniqueData) ? uniqueData : [];
      
      // 关联攻略和景点信息
      const processedData = data.map(item => {
        let scenicInfo = {};
        if (item.intro_id) {
          const intro = strategyMap[item.intro_id];
          if (intro) {
            scenicInfo = scenicMap[intro.scenic_id] || {};
          }
        }
        return { ...item, scenicInfo };
      });

      // 按时间排序，最新的在前
      processedData.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
      setFilteredData(processedData);
      setLoading(false);
    })
    .catch(error => {
      console.error('获取全部数据出错:', error);
      setFilteredData([]);
      setLoading(false);
    });
};

  /**
   * 删除收藏项
   * @param {number} id - 收藏项ID
   */
 const handleDeleteCollectItem = (id) => {
  // 调用API删除收藏项
  deleteCollectItem(id)
    .then(() => {
      // 删除成功后刷新当前选项卡数据
      const userId = sessionStorage.getItem("userid");
      const type = tabs[activeTab].type;
      if (type === null) {
        fetchAllDataWrapper(userId);
      } else {
        fetchCollectDataWrapper(userId, type);
      }
    })
    .catch(error => {
      console.error('删除收藏项出错:', error);
      // 可以添加用户提示
    });
};
  /**
   * 选项卡点击处理
   * @param {number} index - 选项卡索引
   * @param {number} status - 选项卡状态
   * @param {number} type - 数据类型
   */
  const handleTabClick = (index, status, type) => {
    // 更新选项卡状态和页面标题
    setActiveTab(index);
    setPageTitle(tabs[index].name);

    const userId = sessionStorage.getItem("userid");
    if (userId) {
      // 根据选项卡类型获取对应数据
      if (type === null) {
        fetchAllDataWrapper(userId);
      } else {
        fetchCollectDataWrapper(userId, type);
      }
    } else {
      // 用户未登录处理
      console.error('用户ID不存在');
      setFilteredData([]);
      setLoading(false);
    }
  };

  /**
   * 渲染收藏项列表
   * @returns {JSX.Element} 收藏项列表UI
   */
  const renderCollectItems = () => {
    // 处理加载状态
    if (loading) return <div style={{ textAlign: 'center', padding: '20px' }}>加载中...</div>;
    if (!filteredData || filteredData.length === 0) return <div style={{ textAlign: 'center', padding: '20px' }}>暂无数据</div>;

    // 根据当前选项卡类型过滤数据
    const currentType = tabs[activeTab].type;
    const displayData = currentType === null 
     ? filteredData  // 全部 - 显示所有数据
      : filteredData.filter(item => item.type === currentType); // 收藏或点赞 - 根据类型过滤

    // 渲染收藏项卡片
    return displayData.map((item, index) => {
      const scenicInfo = item.scenicInfo || {};
      const imgUrl = scenicInfo.img? `${imgUrl}${scenicInfo.img}` : defaultimg;
      const scenicName = scenicInfo.name || '未知景点';

      return (
        <div
          key={item.id || index}
          className="collect"
          onClick={() => {
            // 点击卡片时保存景区信息并跳转到景区详情页
            if (scenicInfo.id) {
              sessionStorage.setItem('jingid', scenicInfo.id); // 存储景区ID
              sessionStorage.setItem('jingdata', JSON.stringify(scenicInfo)); // 存储景区数据
            }
            navigate('/scenicdetails');
          }}
        >
          <img
            src={imgUrl}
            alt={scenicName}
            onError={(e) => {
              // 图片加载失败时显示默认图片
              e.target.src = defaultimg;
            }}
          />
          <div className="collect-con">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '15px' }}>
              <p>{scenicName}</p>
              <img
                src={rbsImg}
                alt="删除"
                onClick={(e) => {
                  // 阻止事件冒泡，只触发删除操作
                  e.stopPropagation();
                  handleDeleteCollectItem(item.id);
                }}
                style={{ cursor: 'pointer', width: '20px', height: '20px' }}
              />
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '13px', color: '#636363' }}>
              <p>{item.type === 1? '收藏' : '点赞'}</p>
              <p style={{ marginRight: '5px' }}>万景千言</p>
            </div>
            <span>{item.create_time}</span>
          </div>
        </div>
      );
    });
  };

  /**
   * 渲染选项卡导航栏
   * @returns {JSX.Element} 选项卡导航UI
   */
  const renderTabs = () => {
    return tabs.map((tab, index) => (
      <div
        key={index}
        className="items"
        style={{
          width: '15%',
          display: 'flex',
          justifyContent: 'center',
          marginLeft: '1%',
          color: activeTab === index? '#2a82e4' : '#63637c',
          cursor: 'pointer',
          transition: 'all 0.5s'
        }}
        onClick={() => handleTabClick(index, tab.status, tab.type)}
      >
        <p style={{ marginTop: '5px' }}>{tab.name}</p>
      </div>
    ));
  };

  // 组件UI结构
  return (
    <div style={{ fontFamily: 'Arial, sans-serif', maxWidth: '100%', margin: 0, padding: 0 }}>
      {/* 顶部导航栏 */}
      <div className="top" style={topStyle}>
        <div style={topContainerStyle}>
          <div className="left" style={leftStyle}>
            <img src={leftImg} alt="返回" onClick={goBack} style={iconStyle} />
            <div className="line" style={lineStyle}></div>
            <img id="hourse" src={hourse3Img} alt="首页" onClick={goHome} style={homeIconStyle} />
          </div>
        </div>
        <p style={{ marginLeft: '-12px' }}>{pageTitle}</p>
      </div>

      {/* 选项卡导航 */}
      <div className="option">
        <div className="option-card" style={optionCardStyle}>
          <div className="options" style={optionsStyle}>
            <div className="option-one" style={optionOneStyle}>
              {renderTabs()}
            </div>
          </div>
          <div className="options-div" style={optionsDivStyle}>
            <div style={{
             ...indicatorStyle,
              marginLeft: activeTab === 0? '3%' : activeTab === 1? '19%' : '35%'
            }}></div>
          </div>
        </div>
      </div>

      {/* 提示信息 */}
      <div style={hintStyle}>
        <span style={hintTextStyle}>
          可删除不感兴趣的景区，以便于我们更精准的为推荐
        </span>
      </div>

      {/* 收藏列表 */}
      <div className="collect-big">
        {renderCollectItems()}
      </div>

      {/* 内联样式定义 */}
      <style jsx>{`
       .collect {
          margin-top: 5px;
          width: 100%;
          height: 80px;
          display: flex;
          align-items: center;
          justify-content: space-around;
          border-bottom: 1px solid #f0f0f0;
          padding: 10px 0;
        }

       .collect img {
          width: 25%;
          height: 90%;
          object-fit: cover;
          border-radius: 4px;
        }

       .collect-con {
          width: 70%;
          height: 90%;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
        }

       .collect-con span {
          color: #c2c2c2;
          font-size: 14px;
        }
      `}</style>
    </div>
  );
};

// 样式对象定义
const topStyle = {
  width: '100%',
  height: '40px',
  color: '#636363',
  display: 'flex',
  fontSize: '14px',
  textAlign: 'center',
  alignItems: 'center',
  borderBottom: '1px #e1e1 solid'
};

const topContainerStyle = {
    display: 'flex',
    alignItems: 'center',
    whiteSpace: 'nowrap',
    width: '50%',
    justifyContent: 'space-between'
};

const leftStyle = {
    width: '65px',
    height: '25px',
    marginLeft: '10px',
    display: 'flex',
    justifyContent: 'space-around',
    alignItems: 'center',
    border: '1px #d4d4d4 solid',
    borderRadius: '20px',
    backgroundColor: '#ffffff'
};

const iconStyle = {
    width: '15px',
    height: '15px',
    cursor: 'pointer'
};

const lineStyle = {
    width: '1px',
    height: '60%',
    backgroundColor: '#d7c3ac'
};

const homeIconStyle = {
    width: '20px',
    height: '20px',
    cursor: 'pointer'
};

const optionCardStyle = {
    display: 'flex',
    fontSize: '15px',
    color: '#636363',
    flexDirection: 'column',
    justifyContent: 'space-around',
    alignItems: 'center',
    width: '100%',
    backgroundColor: '#ffffff',
    position: 'relative'
};

const optionsStyle = {
    display: 'flex',
    fontSize: '15px',
    position: 'relative',
    marginTop: '5px',
    alignItems: 'center',
    justifyContent: 'space-between',
    width: '100%'
};

const optionOneStyle = {
    display: 'flex',
    fontSize: '15px',
    marginTop: '5px',
    alignItems: 'center',
    width: '100%'
};

const optionsDivStyle = {
    display: 'flex',
    fontSize: '15px',
    alignItems: 'center',
    width: '100%',
    marginTop: '5px'
};

const indicatorStyle = {
    width: '10%',
    height: '3px',
    backgroundColor: '#2a82e4',
    transition: 'all 0.5s'
};

const hintStyle = {
    marginTop: '50px',
    marginBottom: '10px'
};

const hintTextStyle = {
    color: 'red',
    fontSize: '13px',
    marginLeft: '10px',
    whiteSpace: 'nowrap'
};

export default BrowseRecord;    